package com.winning.gjhlht.ihe.hl7ClientService.data.service;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.sql.Clob;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.xml.XMLSerializer;

import org.apache.log4j.Logger;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.quartz.CronTrigger;
import org.quartz.TriggerUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cownew.ctk.common.RandomGUID;
import com.ctc.wstx.util.DataUtil;
import com.framework.helper.PageHelper;
import com.framework.helper.ServerSQLExecutorUtils;
import com.framework.server.db.bean.PageBean;
import com.framework.server.db.bean.PageQueryBean;
import com.framework.server.manager.SQLConfigLoader;
import com.winning.common.Constans;
import com.winning.common.beans.ihe.IHERequestBodyBean;
import com.winning.common.beans.ihe.IHERequestItemBean;
import com.winning.common.beans.xmlTemp.XMLTempBeanManager;
import com.winning.common.beans.xmlTemp.XMLTempConfigBean;
import com.winning.common.data.service.PlatBasicDataService;
import com.winning.common.tools.SQLTool;
import com.winning.common.tools.XMLTool;
import com.winning.core.net.CXFWebserviceClent;
import com.winning.gjhlht.ihe.cdaService.service.IBaseCDACreaterServiceInter;
import com.winning.gjhlht.ihe.common.IHEConstans;
import com.winning.gjhlht.ihe.hl7ClientService.data.dao.inter.IHEDataDaoInter;

/**
 * 互联互通服务
 * 类名称：IHEDataService
 * 类描述：
 * 创建人：zq
 * 创建时间：2017-2-8 上午8:28:22
 * 修改人：zq
 * 修改时间：2017-2-8 上午8:28:22
 * 修改备注：
 */
@Service(value = "com.winning.gjhlht.ihe.hl7ClientService.data.service.IHEDataService")
public class IHEDataService extends IHEBaseDataService {
    private static Logger LOGGER = Logger.getLogger("pbsLoger");

    //个人健康档案注册服务id
    private static final String GR_JKDAZC_SERVICE_ID = "CDA_GRXX_TEMP_001";

    //张家港患者注册服务ID
    private static final String ZJG_HZZC_SERVICE_ID = "GRZC_ZJG_TEMP_002";

    @Autowired
    private IHEDataDaoInter iheDataDao = null;

    @Autowired
    private PlatBasicDataService platBasicDataService = null;

    @Autowired
    private IBaseCDACreaterServiceInter baseCDACreaterService = null;


    /**
     * 下载一份CDA文件
     * 方法名称: downLoadCDAFile
     *
     * @param
     * @return void  返回类型说明<br/>
     * @throws <br/>
     * @author zq@winning.com.cn<br/>
     * 创建时间：2017-2-9/下午1:15:37<br/>
     */
    public void downLoadCDAFile(String ID, HttpServletResponse response) {
        try {
            //数据源
            String dbDataSourceID = getDBDataSouorceID(ZJG_HZZC_SERVICE_ID);

            String sql = "SELECT XMLCONTENT,SOURCEPATIENTNAME,TITLE,WDLX FROM IHE_CDA_DOC_BUFFER WHERE ID = ?";


            List<HashMap<String, Object>> list = ServerSQLExecutorUtils.executeQueryOtherDB(sql, new Object[]{ID}, dbDataSourceID);

            if (list != null && list.size() > 0) {
                Map<String, Object> map = list.get(0);


                String xmlStr = "";
                if (dbDataSourceID.indexOf(Constans.DATA_SOURCE_ORACLE_TAG) > -1) {
                    Clob clob = (Clob) map.get("XMLCONTENT");

                    xmlStr = ClobToString(clob);
                } else {
                    xmlStr = map.get("XMLCONTENT").toString();
                }


                Document xmlDoc = XMLTool.getDocumentFromXMLString(xmlStr, true);

                //患者名称
                String userName = map.get("SOURCEPATIENTNAME").toString();

                //文档类型
                String wdlx = map.get("WDLX").toString();

                //文件名
                String fileName = userName + "_" + wdlx + "_CDA.xml";

                LOGGER.info("-->生成XML文档名称:" + fileName);

                response.reset();
                response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
                //response.addHeader("Content-Length", "");
                response.setContentType("application/octet-stream;charset=UTF-8");
                OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
                outputStream.write(xmlDoc.asXML().getBytes("UTF-8"));
                outputStream.flush();
                outputStream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error(e, e.fillInStackTrace());
        }
    }


}




